﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Chefbook.DataObjects.XmlSerialization
{
    /// <summary>
    /// Contains extension methods for working with xml strings
    /// </summary>
    public static class XmlExtensionMethods
    {
        /// <summary>
        /// Escapes an XML string with literals
        /// </summary>
        /// <param name="value">The string to escape</param>
        /// <returns>The escaped string</returns>
        public static string EscapeXml(this string value)
        {
            string xml = value;
            if (!string.IsNullOrEmpty(xml))
            {
                // replace literal values with entities
                xml = xml.Replace("&", "&amp;");
                xml = xml.Replace("<", "&lt;");
                xml = xml.Replace(">", "&gt;");
                xml = xml.Replace("\"", "&quot;");
                xml = xml.Replace("'", "&apos;");
            }
            return xml;
        }

        /// <summary>
        /// Unescapes an escaped XML string
        /// </summary>
        /// <param name="value">The string to unescape</param>
        /// <returns>The unescaped string</returns>
        public static string UnescapeXml(this string value)
        {
            string unxml = value;
            if (!string.IsNullOrEmpty(unxml))
            {
                // replace entities with literal values
                unxml = unxml.Replace("&apos;", "'");
                unxml = unxml.Replace("&quot;", "\"");
                unxml = unxml.Replace("&gt;", ">");
                unxml = unxml.Replace("&lt;", "<");
                unxml = unxml.Replace("&amp;", "&");
            }
            return unxml;
        }
    }
}
